import { defineStore } from "pinia"
import { reactive, ref, onMounted, nextTick } from "vue"
import { Get_one_music, Get_recommend } from "@/apis/web/WebApi"
import { format } from "@/utils/formatTime"
import { type WebEssay } from "@/types/WebEssay"
export const AppStore = defineStore("appstore", () => {
    const scro_position = ref(0)
    onMounted(() => {
        get_Music__one(currentStaeMusic.value)
        get_recommend_list()
    })
    //推荐文章列表
    const recommend_list = reactive<WebEssay[]>([])
    let currentStaeMusic = ref(0)
    let isplay = ref(false)
    let preshow = ref(false)
    let imgurl = ref('')
    let isadmin = ref<any>(false)
    let other_music = ref({
        url_radio: "",
        url_img: "",
        singer: "",
        musicname: ""
    })
    //音乐总数
    let countNum = ref(0)
    //获取单个musice
    const get_Music__one = async (skp: number) => {
        const result: any = await Get_one_music(skp)
        console.log(result)
        const { count, music_one } = result.data
        countNum.value = count
        other_music.value.url_img = music_one.Music_img
        other_music.value.singer = music_one.singer
        other_music.value.musicname = music_one.musicname
        if (music_one.local_address.trim()) {
            other_music.value.url_radio = music_one.local_address
        } else {
            other_music.value.url_radio = music_one.network_address
        }
    }
    //上一首
    const get_left = async () => {
        currentStaeMusic.value = currentStaeMusic.value - 1
        if (currentStaeMusic.value < 0) {
            currentStaeMusic.value = countNum.value - 1
            console.log(currentStaeMusic.value, "不对")
        } else {
            console.log(currentStaeMusic.value, '合适')
        }
        nextTick(async () => {
            await get_Music__one(currentStaeMusic.value)
        })
    }
    //下一首
    const get_right = async () => {
        currentStaeMusic.value = currentStaeMusic.value + 1
        if (currentStaeMusic.value > countNum.value - 1) {
            currentStaeMusic.value = 0
        } else {
        }
        nextTick(async () => {
            await get_Music__one(currentStaeMusic.value)
        })
    }

    const get_recommend_list = async () => {
        const result = await Get_recommend()
        result.data.forEach((item: any, index: number) => {
            result.data[index].publish_time = format.formatDate(item.publish_time)
        });
        Object.assign(recommend_list, result.data)
    }
    return {
        isplay,
        preshow,
        imgurl,
        isadmin,
        other_music,
        get_left,
        get_right,
        recommend_list,
        scro_position
    }
})